import { NearFarScalar } from 'cesium'
import * as Cesium from 'cesium'
import { getDeviceBySn } from '@/api/manage'
import { ELocalStorageKey, EDeviceTypeName } from '@/types'
import { de } from 'element-plus/es/locale'
import { CURRENT_CONFIG } from '../api/http/config'
interface IInitMarker {
  type?: number
  name?: string
  sn: string
  lng?: number
  lat?: number
  height?: number
  head?: number
  pitch?: number
  roll?: number
}
type MakeRequired<T, K extends keyof T> = T & Required<Pick<T, K>>;
export class DeviceTsaUpdate {
  private markers: any = {}
  private viewer: Cesium.Viewer | null = null

  init(viewer: Cesium.Viewer) {
    this.viewer = viewer
  }

  initMarker({ type, name, sn, lng, lat, height }: IInitMarker) {
    console.log('initMarker', { type, name, sn, lng, lat, height })
    const translucencyByDistance2 = new NearFarScalar(20000, 1, 150000, 0.7)
    if (this.markers[sn]) {
      return
    }

    const heading = Cesium.Math.toRadians(135)
    const pitch = 0
    const roll = 0
    const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll) //
    const orientation = Cesium.Transforms.headingPitchRollQuaternion(
      Cesium.Cartesian3.fromDegrees(lng || 116.2149169889074, lat || 39.905719474154104, height || 1),
      hpr
    )
    this.markers[sn] = {
      id: sn,
      name: sn,
      key: '11111111',
      position: Cesium.Cartesian3.fromDegrees(lng || 116.2149169889074, lat || 39.905719474154104, height || 1),
      orientation: orientation,
      model: {
        uri: './uav07.glb',
        minimumPixelSize: 0.1,
        // 模型的最大比例尺大小。 minimumPixelSize的上限。
        maximumScale: 0.1,
        translucencyByDistance: new Cesium.NearFarScalar(20000, 1, 100000, 1),
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 50000), // 可视范围
        modelMatrix: ' Matrix4.IDENTITY',

      },
      label: {
        text: name,
        // 字体大小
        font: '18px sans-serif',
        // FILL填充/OUTLINE描边/FILL_AND_OUTLINED填充描边
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
        // 描边颜色
        outlineColor: Cesium.Color.WHITE,
        // 描边宽度
        outlineWidth: 5,
        // 字体颜色
        fillColor: Cesium.Color.BLACK,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // default
        pixelOffset: new Cesium.Cartesian2(0, -50), // 视角偏移
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 50000), // 可视范围
        translucencyByDistance: translucencyByDistance2
      }
      // 自动计算前进方向
      // orientation: new Cesium.VelocityOrientationProperty(positionProperty),
    }

    this.viewer!.entities.add(this.markers[sn])
  }

  // 移除
  removeMarker(sn: string) {
    if (!this.markers[sn]) {
      return
    }
    // 当无人机断开连接，清除广告牌
    this.viewer!.entities.removeById(this.markers[sn].id)
    delete this.markers[sn]
    // delete paths[sn]
  }

  getAngle(lng_a: number, lat_a: number, lng_b: number, lat_b: number) {
    const a = ((90 - lat_b) * Math.PI) / 180
    const b = ((90 - lat_a) * Math.PI) / 180
    const AOC_BOC = ((lng_b - lng_a) * Math.PI) / 180
    const cosc = Math.cos(a) * Math.cos(b) + Math.sin(a) * Math.sin(b) * Math.cos(AOC_BOC)
    const sinc = Math.sqrt(1 - cosc * cosc)
    const sinA = (Math.sin(a) * Math.sin(AOC_BOC)) / sinc
    const A = (Math.asin(sinA) * 180) / Math.PI
    let res = 0
    if (lng_b > lng_a && lat_b > lat_a) res = A
    else if (lng_b > lng_a && lat_b < lat_a) res = 180 - A
    else if (lng_b < lng_a && lat_b < lat_a) res = 180 - A
    else if (lng_b < lng_a && lat_b > lat_a) res = 360 + A
    else if (lng_b > lng_a && lat_b === lat_a) res = 90
    else if (lng_b < lng_a && lat_b === lat_a) res = 270
    else if (lng_b === lng_a && lat_b > lat_a) res = 0
    else if (lng_b === lng_a && lat_b < lat_a) res = 180
    return res
  }

  // 添加机场
  public async addAirport({ sn, lng, lat }: { sn: string; lng: number; lat: number }) {
    const marker = this.markers[sn]
    if (!marker) {
      // await getDeviceBySn(localStorage.getItem(ELocalStorageKey.WorkspaceId)!, sn).then((data) => {
      // console.log('getDeviceBySn------------------', data)
      // if (data.code !== 1) {
      //   // message.error(data.message)
      //   console.error(data.message)
      //   return
      // }
      let r1 = 1500
      let r2 = 1500
      const translucencyByDistance2 = new Cesium.NearFarScalar(20000, 1, 100000, 1)
      let deviationAngle
      // for (const k of CURRENT_CONFIG.deviationAngleAtTheAirport) {
      // if (k.title === data.nickname) {
      // deviationAngle = this.getAngle(...k.coordinatesArr)
      // }
      // }

      const heading = Cesium.Math.toRadians(deviationAngle || 0)
      const pitch = 0
      const roll = 0
      const lan = 119.40489996028663
      const LAA = 32.18677155419461
      const hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll)
      const orientation = Cesium.Transforms.headingPitchRollQuaternion(
        Cesium.Cartesian3.fromDegrees(lng || +lan, lat || +LAA, 1),
        hpr
      )

      this.markers[sn] = {
        id: sn,
        name: name,
        key: '11111111',
        position: Cesium.Cartesian3.fromDegrees(lng || +lan, lat || +LAA, 2),
        orientation: orientation,
        model: {
          uri: './close.glb',
          minimumPixelSize: 0.1,
          // 模型的最大比例尺大小。 minimumPixelSize的上限。
          maximumScale: 0.1,
          translucencyByDistance: new Cesium.NearFarScalar(20000, 1, 100000, 1),
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 50000) // 可视范围
          // modelMatrix: ' Matrix4.IDENTITY',
        },
        label: {
          text: name,
          // 字体大小
          font: '18px sans-serif',
          // FILL填充/OUTLINE描边/FILL_AND_OUTLINED填充描边
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          // 描边颜色
          outlineColor: Cesium.Color.WHITE,
          // 描边宽度
          outlineWidth: 5,
          // 字体颜色
          fillColor: Cesium.Color.BLACK,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // default
          pixelOffset: new Cesium.Cartesian2(0, -50), // 视角偏移
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 50000), // 可视范围
          translucencyByDistance: translucencyByDistance2
        }
      }
      console.log(this.markers[sn], 'this.markers[sn]', this)
      const marker = this.viewer!.entities.add(this.markers[sn])
      console.log(marker, 'marker')
      this.markers[sn + 1] = {
        id: sn + 1,
        name: name,
        key: '11111111',
        position: Cesium.Cartesian3.fromDegrees(lng || +lan, lat || +LAA, 1),
        // orientation: orientation,
        ellipse: {
          show: true,
          sizeInMeters: true,
          semiMinorAxis: new Cesium.CallbackProperty(function () {
            r1 = r1 + 10
            if (r1 >= 3000) {
              r1 = 0
            }
            return r1
          }, false),
          semiMajorAxis: new Cesium.CallbackProperty(function () {
            r2 = r2 + 10
            if (r2 >= 3000) {
              r2 = 0
            }
            return r2
          }, false),
          material: new Cesium.StripeMaterialProperty({
            evenColor: Cesium.Color.fromCssColorString('rgba(0, 201, 87, 0.1)'),
            oddColor: Cesium.Color.fromCssColorString('rgba(0, 201, 87, 0.1)')
          }),
          height: 1.0,
          heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
          outline: true,
          outlineColor: Cesium.Color.fromCssColorString('rgba(0, 201, 87, 0.5)'),
          translucencyByDistance: translucencyByDistance2
        }
      }

      this.viewer!.entities.add(this.markers[sn + 1])
      //   // // 添加广告牌
      //   // // this.initMarker({ sn, name, lng, lat })
      //   marker = this.markers[sn]
      //   // this.initMarker({ type: data.data.domain, name, sn, lng, lat })
      // })
    }
  }

  addMarker({ type, name, sn, lng, lat, height }: IInitMarker) {
    getDeviceBySn(localStorage.getItem(ELocalStorageKey.WorkspaceId)!, sn).then((data) => {
      console.log('getDeviceBySn', data)
      if (data.code !== 1) {
        // message.error(data.message)
        console.error(data.message)
        return
      }
      // 添加广告牌
      this.initMarker({ type: data.data.domain, name, sn, lng, lat })
    })
  }

  /*
  sn: string -> 机器的标识
  name: string -> 要渲染的名称
  lng: string -> 经度
  lat: string -> 纬度
  height: string -> 高度
  s:object -> 当前要渲染机器的参数
  */
  moveTo({ sn, name, lng, lat, height, head, pitch, roll }: MakeRequired<IInitMarker, 'lng' | 'lat' | 'head' | 'pitch' | 'roll'>) {
    let marker = this.markers[sn]
    if (!marker) {
      this.addMarker({ sn, name, lng, lat, height })
      marker = this.markers[sn]
    } else {
      if (this.viewer!.entities.getById(this.markers[sn].id)) {
        this.viewer!.entities.getById(this.markers[sn].id)!.position = new Cesium.ConstantPositionProperty(
          Cesium.Cartesian3.fromDegrees(lng, lat, height)
        )
        const hpr = new Cesium.HeadingPitchRoll(
          Cesium.Math.toRadians(+head + 60),
          Cesium.Math.toRadians(pitch),
          Cesium.Math.toRadians(roll)
        )

        const orientation = new Cesium.ConstantProperty(
          Cesium.Transforms.headingPitchRollQuaternion(
            Cesium.Cartesian3.fromDegrees(lng, lat, height),
            hpr
          )
        )

        this.viewer!.entities.getById(this.markers[sn].id)!.orientation = orientation

        // if (this.viewer.entities.getById(this.markers[sn].id).name !== '遥控器') {
        //   const hpr = new Cesium.HeadingPitchRoll(
        //     Cesium.Math.toRadians(s[sn].attitude_head),
        //     Cesium.Math.toRadians(s[sn].attitude_pitch),
        //     Cesium.Math.toRadians(s[sn].attitude_roll)
        //   )
        //   this.viewer.entities.getById(this.markers[sn].id).orientation = Cesium.Transforms.headingPitchRollQuaternion(
        //     Cesium.Cartesian3.fromDegrees(s[sn].longitude, s[sn].latitude, s[sn].height),
        //     hpr
        //   )
        // }
      }
    }
  }

  adjustTheAngleOfView(b: boolean, id: string) {
    if (!this.viewer) return
    const shipModel = this.viewer!.entities.getById(id)

    if (b && shipModel) {
      // 设置视角观察偏移量（相对实体坐标系）
      shipModel.viewFrom = new Cesium.ConstantProperty(new Cesium.Cartesian3(
        -50, // X 轴偏移（正前负后）
        -30, // Y 轴偏移（正右负左）
        80 // Z 轴偏移（高度）
      ))
      this.viewer.trackedEntity = shipModel
    } else {
      this.viewer.trackedEntity = undefined
    }
    // const scene = this.viewer!.scene
    // if (v === '视角跟随') {
    //   const drone = this.viewer.entities.getById('1231231231')
    //   const camera = this.viewer.camera
    //   console.log(this.viewer?.trackedEntity)
    //   // this.viewer.trackedEntity = drone
    //   // this.viewer?.camera.setView({
    //   //   destination: drone.position.getValue(this.viewer.clock.currentTime),
    //   //   orientation: {
    //   //     heading: Cesium.Math.toRadians(90.0), // east, default value is 0.0 (north)
    //   //     pitch: Cesium.Math.toRadians(-90), // default value (looking down)
    //   //     roll: 0.0 // default value
    //   //   }
    //   // })
    //   // 设置观察偏移量（X: 后方距离，Y: 右侧距离，Z: 高度）
    //   // drone.viewFrom = new Cesium.Cartesian3(-300, 0, 50) // 在实体后方300米，高度50米
    //   // this.viewer.trackedEntity = drone
    //   // this.viewer.trackedEntity.viewFrom = new Cesium.Cartesian3(-300, 0, 50)
    //   console.log('检查变化', drone)
    //   // drone?.position?.definitionChanged.addEventListener((ite) => {
    //   //   console.log('位置发生变化了', ite)
    //   // })
    //   this.viewer!.trackedEntity = drone
    //   // 帧(渲染)监听
    //   this.viewer.scene.preUpdate.addEventListener(() => {
    //     // this.viewer.trackedEntity.viewFrom = new Cesium.Cartesian3(-300, 0, 50)
    //     // this.viewer.trackedEntity.viewFrom = new Cesium.Cartesian3(-300, 0, 50)
    //     // 获取当前位置
    //     // adjust()
    //     // const currentPosition = drone.position.getValue(this.viewer.clock.currentTime)
    //     // 获取当前方向
    //     // const currentOrientation = drone.orientation.getValue(this.viewer.clock.currentTime)
    //     // console.log('当前位置', currentPosition, '当前方向', currentOrientation)
    //   })

    //   const adjust = () => {
    //     // 获取位置
    //     const center = drone.position.getValue(this.viewer.clock.currentTime)
    //     // 获取偏向角
    //     const ori = drone.orientation.getValue(this.viewer.clock.currentTime)

    //     // 1、由四元数计算三维旋转矩阵
    //     const mtx3 = Cesium.Matrix3.fromQuaternion(ori)

    //     // 2、计算四维转换矩阵：
    //     const mtx4 = Cesium.Matrix4.fromRotationTranslation(mtx3, center)

    //     // 3、计算角度：
    //     const hpr = Cesium.Transforms.fixedFrameToHeadingPitchRoll(mtx4)

    //     // 获取角度（弧度）
    //     const headingTemp = hpr.heading
    //     const pitchTemp = hpr.pitch

    //     // 调整角度为第一人称，注意调整的角度
    //     const heading = Cesium.Math.toRadians(Cesium.Math.toDegrees(headingTemp) + 90)
    //     const pitch = Cesium.Math.toRadians(Cesium.Math.toDegrees(pitchTemp) - 12)

    //     // 视角高度，根据模型大小调整
    //     const range = 300.0
    //     console.log(this.viewer?.scene.screenSpaceCameraController)
    //     // this.viewer.scene.screenSpaceCameraController.enableZoom = false // . 禁止视角缩放
    //     // this.viewer.scene.screenSpaceCameraController.enableRotate = false // 禁止左键拖动视角
    //     // this.viewer.scene.screenSpaceCameraController.enableTilt = false // 禁止中键旋转视角

    //     // 动态改变模型视角
    //     this.viewer?.camera.lookAt(center)
    //     // this.viewer.camera.lookAt(center, new Cesium.HeadingPitchRange(heading, pitch, range))
    //     console.log('heading', Cesium.Math.toDegrees(heading))
    //   }
    //   // adjust()
    //   // const onTickEvent = this.viewer.clock.onTick.addEventListener(adjust)

    //   // onTickEvent = this.viewer.clock.onTick.addEventListener(adjust)
    // } else if (v === '取消跟随') {
    //   // onTickEvent && onTickEvent()
    //   this.viewer.trackedEntity = undefined
    // }
    // onTickEvent = this.viewer.clock.onTick.addEventListener(adjust)
  }
}

export default new DeviceTsaUpdate()
